"""
GPS处理模块
GPS handling module for location data
"""

import serial
import time
import logging
from config import GPS_CONFIG, SERIAL_CONFIG

logger = logging.getLogger(__name__)

class GPSHandler:
    def __init__(self):
        self.port = SERIAL_CONFIG['gps_port']
        self.baudrate = SERIAL_CONFIG['gps_baudrate']
        self.timeout = SERIAL_CONFIG['timeout']
        
    def get_location_info(self):
        """获取当前GPS位置信息"""
        try:
            gps_ser = None
            try:
                gps_ser = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
                if gps_ser.isOpen():
                    logger.info("GPS串口临时打开成功")
                    
                    # 尝试读取GPS数据
                    for attempt in range(GPS_CONFIG['max_attempts']):
                        if gps_ser.inWaiting():
                            line = gps_ser.readline().decode('utf-8', errors='ignore').strip()
                            if line.startswith('$GNGGA') or line.startswith('$GPGGA'):
                                location_data = self._parse_gga_sentence(line)
                                if location_data:
                                    return location_data
                        time.sleep(GPS_CONFIG['read_timeout'])
                    
                    logger.warning("GPS信号读取超时")
                    return self._create_no_signal_response()
                    
            except Exception as e:
                logger.error(f"GPS串口操作错误: {e}")
                return self._create_error_response()
            finally:
                if gps_ser and gps_ser.isOpen():
                    gps_ser.close()
                    logger.info("GPS串口已关闭")
                    
        except Exception as e:
            logger.error(f"GPS模块初始化错误: {e}")
            return self._create_unavailable_response()
    
    def _parse_gga_sentence(self, line):
        """解析GNGGA/GPGGA语句"""
        try:
            parts = line.split(',')
            if len(parts) >= 15 and parts[2] and parts[4]:
                # 转换纬度
                lat_deg = float(parts[2][:2])
                lat_min = float(parts[2][2:])
                latitude = lat_deg + lat_min/60.0
                if parts[3] == 'S':
                    latitude = -latitude
                
                # 转换经度
                lon_deg = float(parts[4][:3])
                lon_min = float(parts[4][3:])
                longitude = lon_deg + lon_min/60.0
                if parts[5] == 'W':
                    longitude = -longitude
                
                altitude = float(parts[9]) if parts[9] else None
                satellites = int(parts[7]) if parts[7] else None
                
                return {
                    'latitude': round(latitude, 8),
                    'longitude': round(longitude, 8),
                    'altitude': altitude,
                    'satellites': satellites,
                    'gps_time': parts[1] if parts[1] else None,
                    'location_source': 'GPS'
                }
        except (ValueError, IndexError) as e:
            logger.error(f"GPS数据解析错误: {e}")
        return None
    
    def _create_no_signal_response(self):
        return {
            'latitude': None,
            'longitude': None,
            'altitude': None,
            'satellites': None,
            'gps_time': None,
            'location_source': 'GPS_no_signal'
        }
    
    def _create_error_response(self):
        return {
            'latitude': None,
            'longitude': None,
            'altitude': None,
            'satellites': None,
            'gps_time': None,
            'location_source': 'GPS_error'
        }
    
    def _create_unavailable_response(self):
        return {
            'latitude': None,
            'longitude': None,
            'altitude': None,
            'satellites': None,
            'gps_time': None,
            'location_source': 'unavailable'
        }
